import openpyxl
import argparse
import os
def extract_data(excel_file, sheet_name, search_string):
    try:
        # 加载 Excel 文件
        workbook = openpyxl.load_workbook(excel_file)
        
        # 检查工作表是否存在
        if sheet_name not in workbook.sheetnames:
            return "Error: The specified sheet does not exist in the Excel file."
        
        worksheet = workbook[sheet_name]
        
        # 遍历工作表内容,找到匹配的行
        output_string = ''
        for row in range(2, worksheet.max_row + 1):
            # 获取第一列的值
            first_column = worksheet.cell(row=row, column=1).value
            
            # 检查第一列值是否与搜索字符串完全匹配
            if str(first_column) == search_string:
                # 获取第二列的值
                second_column = worksheet.cell(row=row, column=2).value
                output_string += f"./mugen.sh -f {first_column} -r {second_column} -x\n"
        
        return output_string
    except FileNotFoundError:
        return "Error: The specified Excel file does not exist."
    except Exception as e:
        return f"Error: {str(e)}"

if __name__ == "__main__":
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description="Extract data from an Excel file")
    parser.add_argument("search_string", help="Search string for the first column")
    args = parser.parse_args()

    # 使用固定的文件名和工作表名称
    excel_file = "2403_mugen失败测试用例.xlsx"
    sheet_name = "工作表1"

    # 获取匹配行的数据
    output_string = extract_data(excel_file, sheet_name, args.search_string)
    
    # 创建输出文件夹
    qa_folder = "QAteam/mugen"
    output_folder = os.path.join(qa_folder, f"{args.search_string}")
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    # 输出结果到文件
    output_file = os.path.join(output_folder, f"testlist.txt")
    with open(output_file, 'w', encoding='utf-8') as file:
        file.write(output_string)

    print(f'Output has been saved to {output_file}')
